package com.guanyu.u2cache.caffeine;

import com.guanyu.u2cache.model.MemoryUseClass;
import lombok.Data;

import java.lang.management.ManagementFactory;
import java.lang.management.MemoryMXBean;
import java.util.ArrayList;
import java.util.List;

/**
 * @author zhouyunjian
 * @date 2023/12/08 17:25
 **/
@Data
public class MemoryUseCount {

    public MemoryUseCount() {
        this.memoryUseClasses = new ArrayList<>(100);
    }

    /**
     * 已用缓存大小比例
     */
    private long useCacheNum = 0L;
    /**
     * 本地服务使用缓存大小
     */
    private long localTotalCache;
    /**
     * 缓存列表
     */
    private List<MemoryUseClass> memoryUseClasses;


    public MemoryUseCount calculateMemorySpace() {
//        this.setLocalTotalCache(findLocalCache());
//        U2CacheManager singleton = U2CacheManager.getSingleton();
//        if (CollectionUtil.isEmpty(singleton.cacheMap)) {
//            this.setUseCacheNum(RamUsageEstimator.sizeOfObject(singleton.cacheMap));
//            return this;
//        }
//        Map<String, Map<String, Long>> hotSpotCountMap = singleton.hotSpotCountMap;
//        singleton.cacheMap.forEach((name, cache) -> {
//            ConcurrentMap<@NonNull String, @NonNull Object> cacheMp = cache.asMap();
//            MemoryUseClass unit = new MemoryUseClass();
//            unit.setCacheNames(name);
//            if (ObjectUtil.isNotEmpty(cacheMp)) {
//                cacheMp.forEach((key, value) -> {
//                    unit.addKeyInfo(RamUsageEstimator.sizeOfObject(value), key, hotSpotCountMap.getOrDefault(KeyUtil.createKey(name, key), new HashMap<>(16)));
//                });
//            } else {
//                unit.setSize(RamUsageEstimator.sizeOfObject(cacheMp));
//            }
//            this.setUseCacheNum(this.getUseCacheNum() + unit.getSize());
//            this.memoryUseClasses.add(unit);
//        });
        return this;
    }

    private long findLocalCache() {
        MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();
        long max = memoryMXBean.getHeapMemoryUsage().getMax();
        long noMax = memoryMXBean.getNonHeapMemoryUsage().getMax();
        return max + noMax;
    }


}
